package com.edt.ichannel.api.service.impl;

import cc.edt.iceutils2.number.IceNumberUtils;
import cc.edt.iceutils2.random.IceRandomUtils;
import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.date.IceDateFormatUtils;
import cc.edt.iceutils3.date.IceDateOperationUtils;
import cc.edt.iceutils3.json.IceFastJsonUtils;
import com.edt.ichannel.api.common.constant.CommonConstant;
import com.edt.ichannel.api.common.entity.ActionResult;
import com.edt.ichannel.utils.FileUtil;
import com.edt.ichannel.utils.FtpUtil;
import com.edt.ichannel.utils.SFTPUtil;
import com.edt.ichannel.utils.entity.FtpResult;
import com.edt.ichannel.api.dao.SynDataDao;
import com.edt.ichannel.api.entiy.local.*;
import com.edt.ichannel.api.service.*;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 同步数据服务类
 *
 * @author sl
 */
@Slf4j
@Service
public class SynDataServiceImpl implements SynDataService {
    private static final String SELECT_ALL_STR = "ALL";
    private static final String ACCOUNT_COMPARE_SUBFIX = ".dat";
    private static final String RED_PACKAGE_ORDER_SUBFIX = ".txt";
    private static final String RED_PACKAGE_ORDER_PREFIX = "OFFLINE_ORDER_";
    private static final String RED_PACKAGE_ORDER_RESULT_SUBFIX = "_RESULT";
    private static final String ACTIVITY_STAFF_FILENAME = "BMQNRC+";
    private static final String ACTIVITY_STAFF_FILENAME_SUBFIX = ".TXT";
    private static final String ORDER_CHANNEL_MONTH_KFTP_PREFIX = "PARTNER_INFO_";
    private static final String ORDER_CHANNEL_MONTH_KFTP_SUBFIX = ".REQ";
    private static final String ORDER_CHANNEL_MONTH_RETURN_KFTP_SUBFIX = ".RSP";

    private static final String UNICOMPAY_FILE_RESULT_SUBFIX = "_back.REQ";


    private static final int SELECT_OPEN = 1;
    private static final int SELECT_CLOSE = 2;
    @Resource
    private SynDataDao synDataDao;

    @Resource
    private OrderChannelService orderChannelService;

    @Resource
    private OrderCreditService orderCreditService;

    @Resource
    private InterfaceLogService logService;
    @Resource
    private CommissionService commissionService;
    @Resource
    private WoaccountService woaccountService;
    @Resource
    private AccountCompareService accountCompareService;

    @Resource
    private BonusService bonusService;
    @Resource
    private RedPacketOrderService redPacketOrderService;
    @Resource
    private CityCodeService cityCodeService;
    @Resource
    private RedPacketOrderResultService redPacketOrderResultService;
    @Resource
    private MechanismsService mechanismsService;
    @Resource
    private StaffService staffService;
    @Resource
    private BonusLogService bonusLogService;
    @Resource
    private FirstmoneyLogService firstmoneyLogService;
    @Resource
    private ExpansionService expansionService;
    @Resource
    private ComputeCommissionKdService computeCommissionKdService;

    @Resource
    private PutoutCommissionService putoutCommissionService;

    @Resource
    private OrderCreditCKService orderCreditCKService;
    @Resource
    private OrderCreditKdService orderCreditKdService;
    @Resource
    private UnicomPayReqService unicomPayReqService;

    @Resource
    private EdtApiService edtApiService;

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private OnlineOrderService onlineOrderService;

    @Resource
    private BFService bfService;

    @Resource
    private OrderCreditMonthService orderCreditMonthService;

    @Resource
    private CommissionSuperaddService commissionSuperaddService;

    @Resource
    private FirstOrderCommissionService firstOrderCommissionService;

    @Resource
    private CommissionArriveRuleService commissionArriveRuleService;
    @Resource
    private CommissionArriveService commissionArriveService;
    private static final int MAX_READTIMES = 5;


    @Override
    public void synMechanismsInfo() {
        log.info("------------同步组织结构开始");
        ActionResult result = new ActionResult();
        try {
            //查询dblink组织机构信息
            mechanismsService.mergeMechanismsFromDblink();
            log.info("------------同步组织结构信息成功");
            mechanismsService.updateAllCityCode();
            log.info("------------更新地市信息成功");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (Exception e) {
            log.info("查询数据失败：" + e.getMessage());
            ;
            e.printStackTrace();
        }
        logService.addLog(result, "同步组织机构", "同步组织机构", CommonConstant.INTERFACE_TYPE_SYNMECHANISMS);
        log.info("------------同步组织结构结束");
    }

    @Override
    public void synHrStaff() {
        log.info("------------同步人员开始");
        ActionResult result = new ActionResult();
        try {
            //查询人员
            staffService.mergeStaffFromDblink();
            log.info("更新人员同步成功");
            staffService.updateExpansionMechanismsIdDifferent();
            log.info("将小微渠道组织结构更新为拓展人的组织机构，成功");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (Exception e) {
            log.info("查询人员数据异常：" + e.getMessage());
            e.printStackTrace();
        }

        logService.addLog(result, "同步人员", "同步人员", CommonConstant.INTERFACE_TYPE_SYNSTAFF);
        log.info("------------同步人员结束");

    }


    @Override
    public void synOrderIchannel(int day) {
        ActionResult result = new ActionResult();
        try {
            log.info("------------同步orderIchannel");
            Date date = IceDateOperationUtils.addDays(new Date(), day);
            String nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
            List<OrderChannel> orderChannelList = orderChannelService.selectOrderChannelListJF(null);
//            List<OrderChannel> orderChannelListxxh = orderChannelService.selectOrderChannelListXXH(null);
//            orderChannelList.addAll(orderChannelListxxh);
            String fileName = CommonConstant.FILE_NAME_PREFIX_SYNORDERCHANNEL + nameDateStr +
                    CommonConstant.FILE_NAME_EXTEND_SYNORDERCHANNEL +
                    CommonConstant.FILE_NAME_SUBFIX_SYNORDERCHANNEL;
            String content = getContentList(orderChannelList, fileName);
            FtpUtil.uploadFileAndSaveTemp(CommonConstant.JF_FTP_HOST, CommonConstant.JF_FTP_PASSWPRD,
                    CommonConstant.JF_FTP_USERNAME, CommonConstant.JF_FTP_PORT,
                    CommonConstant.JF_FTP_PATH, fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
            log.info("------------orderIchannel上传文件结束");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
        }
        logService.addLog(result, "同步发展订单", "同步发展订单", CommonConstant.INTERFACE_TYPE_SYNORDERCHANNEL);
    }

    @Override
    //D04
    public void synOrderIchannelMonth(int month) {
        ActionResult result = new ActionResult();
        try {
            log.info("------------同步orderIchannel");
            Date date = IceDateOperationUtils.addMonths(new Date(), month);
            String dateStr = IceDateFormatUtils.dateToString(date, "yyyy-MM");
            String nameDateStr = IceDateFormatUtils.dateToString(new Date(), "yyyyMMdd");
            List<OrderChannel> orderChannelList = orderChannelService.selectOrderChannelMonthListJF(dateStr);
            List<OrderChannel> orderChannelListxxh = orderChannelService.selectOrderChannelMonthListXXH(dateStr);
            orderChannelList.addAll(orderChannelListxxh);
            String fileName = CommonConstant.FILE_NAME_PREFIX_SYNORDERCHANNEL_MONTH + nameDateStr +
                    CommonConstant.FILE_NAME_EXTEND_SYNORDERCHANNEL_MONTH +
                    CommonConstant.FILE_NAME_SUBFIX_SYNORDERCHANNEL_MONTH;

            String content = getContentListMonth(orderChannelList, fileName);
            FtpUtil.uploadFileAndSaveTemp(CommonConstant.JF_FTP_HOST, CommonConstant.JF_FTP_PASSWPRD,
                    CommonConstant.JF_FTP_USERNAME, CommonConstant.JF_FTP_PORT,
                    CommonConstant.JF_FTP_PATH, fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
            log.info("------------orderIchannel上传文件结束");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
        }
        logService.addLog(result, "同步月成功订单订单", "同步月成功发展订单", CommonConstant.INTERFACE_TYPE_SYNORDERCHANNEL);
    }


    @Override
    public void synOrderIchannelDay(int day) {
        ActionResult result = new ActionResult();
        try {
            log.info("------------同步orderIchannel");
            Date date = IceDateOperationUtils.addDays(new Date(), day);
            String dayStr = IceDateFormatUtils.dateToString(date, "yyyy-MM-dd");
            String nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
            List<OrderChannel> orderChannelList = orderChannelService.selectOrderChannelDay(dayStr);
            String fileName = "D05" + nameDateStr + "001" + ".TXT";
            String content = getContentListDay(orderChannelList, fileName);
            FtpUtil.uploadFileAndSaveTemp(CommonConstant.JF1_FTP_HOST, CommonConstant.JF1_FTP_PASSWPRD,
                    CommonConstant.JF1_FTP_USERNAME, CommonConstant.JF1_FTP_PORT,
                    CommonConstant.JF1_FTP_PATH, fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
            orderChannelService.updateD05AddToIsPushOver();
            log.info("------------orderIchannel上传文件结束");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
        }
        logService.addLog(result, "同步日成功订单订单", "同步日成功订单订单", CommonConstant.INTERFACE_TYPE_SYNORDERCHANNEL);
    }

    @Override
    public void synMonthDataFromKafka(String monthStr) {
        ActionResult actionResult = new ActionResult();
        try {
            if (IceStringUtils.isNotBlank(monthStr)) {
                String fileName = ORDER_CHANNEL_MONTH_KFTP_PREFIX + monthStr + ORDER_CHANNEL_MONTH_RETURN_KFTP_SUBFIX;
                actionResult = readKafKaFileAndSave(fileName);
            } else {
                List<String> fileNames = FtpUtil.getFileNames(CommonConstant.K_FTP_HOST, CommonConstant.K_FTP_PASSWPRD, CommonConstant.K_FTP_USERNAME, CommonConstant.K_FTP_PORT,
                        CommonConstant.K_FTP_PATH, CommonConstant.K_FTP_CHARSET);
                if (fileNames != null && fileNames.size() > 0) {
                    for (String fileName :
                            fileNames) {
                        File temFile = new File(CommonConstant.JF_FTP_TMEP_PATH, fileName);
                        if (!temFile.exists()) {
                            actionResult = readKafKaFileAndSave(fileName);
                        }
                    }
                } else {
                    actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                    actionResult.setMessage("没有读取到文件");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            actionResult.setMessage(e.getMessage());
        }
        logService.addLog(actionResult, "同步kafka月回执文件", "同步kafka月回执文件", CommonConstant.INTERFACE_TYPE_SYNFIRSTCHARGE);
    }

    @Override
    public void compareKafkaDataAndSaveError() {
        synDataDao.compareKafkaDataAndSaveError();
    }

    private ActionResult readKafKaFileAndSave(String fileName) {
        ActionResult actionResult = new ActionResult();
        FtpResult result = FtpUtil.readFile(CommonConstant.K_FTP_HOST, CommonConstant.K_FTP_PASSWPRD, CommonConstant.K_FTP_USERNAME,
                CommonConstant.K_FTP_PORT, CommonConstant.K_FTP_PATH, fileName, CommonConstant.K_FTP_CHARSET);
        if (result.isSuccess()) {
            FtpUtil.downloadFile(CommonConstant.K_FTP_HOST, CommonConstant.K_FTP_PASSWPRD, CommonConstant.K_FTP_USERNAME,
                    CommonConstant.K_FTP_PORT, CommonConstant.K_FTP_PATH, fileName, CommonConstant.JF_FTP_TMEP_PATH, fileName);
            if (result.getResultSet() != null) {
                List<EntityForKafkaUniBssInfo> bssInfoList = transStringToKafkaUnibssInfo(result.getResultSet());
                //入库
                saveUniBssInfoList(bssInfoList);
                actionResult.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
                actionResult.setMessage("同步成功");
            }
        } else {
            log.info("文件 " + CommonConstant.K_FTP_PATH + "/" + fileName + "读取失败");
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            actionResult.setMessage(result.getMessage());
        }
        return actionResult;
    }

    private void saveUniBssInfoList(List<EntityForKafkaUniBssInfo> bssInfoList) {
        if (bssInfoList != null && bssInfoList.size() != 0) {
            int count = CommonConstant.BRANCH_COUNT;
            int lastIndex = count;
            for (int index = 0; index < bssInfoList.size(); ) {
                if (lastIndex > bssInfoList.size()) {
                    lastIndex = bssInfoList.size();
                    synDataDao.saveList(bssInfoList.subList(index, lastIndex));
                    break;
                } else {
                    synDataDao.saveList(bssInfoList.subList(index, lastIndex));
                    index = lastIndex;
                    lastIndex = index + (count);
                }
            }
            log.info("list 长度：" + bssInfoList.size());
        } else {
            log.info("list为空");
        }
    }

    @Override
    public void synOrderIchannelMonthToKafKaFtp(String monthStr) {
        log.info("------------synOrderIchannelMonthToKafKaFtp");
        try {
            //账期 格式 yyyymm
            List<FirstmoneyLog> firstmoneyLogs = firstmoneyLogService.selectByMonthStr(monthStr);
            String fileName = ORDER_CHANNEL_MONTH_KFTP_PREFIX + IceDateFormatUtils.dateToString(new Date(), "yyyyMM") + ORDER_CHANNEL_MONTH_KFTP_SUBFIX;
            String content = getSelectFirstMoneyInfoMonth(firstmoneyLogs);
            FtpUtil.uploadFileAndSaveTemp(CommonConstant.K_FTP_HOST, CommonConstant.K_FTP_PASSWPRD,
                    CommonConstant.K_FTP_USERNAME, CommonConstant.K_FTP_PORT,
                    CommonConstant.K_FTP_PATH, fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("------------synOrderIchannelMonthToKafKaFtp end");
        }

    }


    @Override
    public void synFirstMoneyCurrentDay(String dayStr) {
        log.info("-----------------synFirstMoneyCurrentDay 开始");
        try {
            //查询开关 关闭则不继续执行
            int firstMoneyControl = synDataDao.getFirstMoneyControle();
            if (firstMoneyControl == SELECT_OPEN) {
                //关闭开关
                synDataDao.updateFirstMoneyControl(SELECT_CLOSE);
                //查询没收首充数据
                List<OrderChannel> orderChannels = orderChannelService.selectOrderChannelCkWithoutCommissionByDay(dayStr);
                if (orderChannels != null && orderChannels.size() > 0) {

                    for (OrderChannel orderChannel :
                            orderChannels) {
                        commissionService.setCommissiont(orderChannel);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //打开开关
            synDataDao.updateFirstMoneyControl(SELECT_OPEN);
            log.info("-----------------synFirstMoneyCurrentDay 结束");
        }


    }

    @Override
    public void synFirstMoneyAll() {
        log.info("-----------------synFirstMoneyAll start");
        //确保查询所有能执行 如果定时器刚起时，发现每天一次的定时器正在执行则等待直到拿到锁
        int firstMoneyControl = synDataDao.getFirstMoneyControle();
        Date beginDate = new Date();
        while (firstMoneyControl == SELECT_CLOSE) {
            firstMoneyControl = synDataDao.getFirstMoneyControle();
            if (IceDateOperationUtils.betweenMinute(beginDate, new Date()) > 30) {
                break;
            }
        }
        synFirstMoneyCurrentDay(null);
        log.info("-----------------synFirstMoneyAll end");
    }

    @Override
    public void moveFirstMoneyInfoToOrderCredit() {
        synDataDao.moveFirstMoneyInfoToOrderCredit();
    }


    @Override
    public void synFirstCharge(int day) {
        ActionResult actionResult = new ActionResult();
        try {

            int count = 0;
            while (count < MAX_READTIMES) {
                log.info("------------同步首充");
                Date date = IceDateOperationUtils.addDays(new Date(), day - count);
                String nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
                String fileName = CommonConstant.FILE_NAME_PREFIX_SYNFIRSTCHARGE + nameDateStr +
                        CommonConstant.FILE_NAME_EXTEND_SYNFIRSTCHARGE +
                        CommonConstant.FILE_NAME_SUBFIX_SYNFIRSTCHARGE;
                File temFile = new File(CommonConstant.JF_FTP_TMEP_PATH, fileName);
                if (!temFile.exists()) {
                    FtpResult result = FtpUtil.readFile(CommonConstant.JF_FTP_HOST, CommonConstant.JF_FTP_PASSWPRD, CommonConstant.JF_FTP_USERNAME,
                            CommonConstant.JF_FTP_PORT, CommonConstant.JF_FTP_PATH, fileName, CommonConstant.JF_FTP_CHARSET);
                    log.debug("读取结果：\n" + IceFastJsonUtils.toJsonString(result));
                    if (result.isSuccess()) {
                        log.info(FtpUtil.downloadFile(CommonConstant.JF_FTP_HOST, CommonConstant.JF_FTP_PASSWPRD, CommonConstant.JF_FTP_USERNAME,
                                CommonConstant.JF_FTP_PORT, CommonConstant.JF_FTP_PATH, fileName, CommonConstant.JF_FTP_TMEP_PATH, fileName).getMessage());
                        if (result.getResultSet() != null) {
                            List<OrderCredit> orderCredits = transStringToOrderCredit(result.getResultSet());
                            //入库
                            orderCreditService.saveOrderCreditList(orderCredits);

                        }
                        actionResult.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
                        actionResult.setMessage("同步成功");
                        break;
                    } else {
                        log.info("文件 " + CommonConstant.JF_FTP_PATH + "/" + fileName + "读取失败 尝试读取前一天文件...");
                        actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                        actionResult.setMessage(result.getMessage());
                    }
                } else {
                    log.info("文件已经读取过：" + IceFastJsonUtils.toJsonString(temFile));
                    actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                    actionResult.setMessage("文件已经读取过：" + IceFastJsonUtils.toJsonString(temFile));
                    break;
                }
                count++;
            }
            log.info("------------同步首充结束");
        } catch (Exception e) {
            e.printStackTrace();
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            actionResult.setMessage(e.getMessage());
        }
        logService.addLog(actionResult, "同步首充", "同步发首充", CommonConstant.INTERFACE_TYPE_SYNFIRSTCHARGE);

    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void computBonus(String batchCode) {
        String key = "COMPUTBONUS";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("------------计算发展奖 " + batchCode);
                List<OrderCredit> orderCredits;
                log.info("批次：" + batchCode);
                if (IceStringUtils.isBlank(batchCode)) {
                    orderCredits = orderCreditService.selectNeedComputBonus(null);
                } else {
                    orderCredits = orderCreditService.selectNeedComputBonus(batchCode);
                }
                log.info("将要计算的发展奖集合：" + orderCredits.size());

                for (OrderCredit orderCredit : orderCredits) {
                    if (orderCredit.getFirstMoney() == 0) {
                        continue;
                    }
//                if (IceDateOperationUtils.isAfter(orderCredit.getOrderDate(), orderCredit.getFirstDate())) {
//                    continue;
//                }
                    BonusLog bonusLog = bonusLogService.selectBonusLogByOrderCode(orderCredit.getOrderCode());
                    if (bonusLog != null) {
                        continue;
                    }
                    //过滤掉已经有计算发展奖的数据
                    if (orderCredit.getBonusMoney() == 0) {
                        bonusService.setBonus(orderCredit);
                    }
                }
                log.info("------------计算发展奖结束");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("计算发展奖异常  批次号：" + batchCode + " 异常信息：" + e.getMessage());
                throw new RuntimeException(e);
            }

        } else {
            log.info("computBonus 有线程在执行");
        }

    }

    @Override
    public void computBonusSuperadd() {
        String key = "COMPUTBONUSSUPERADD";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("------------computBonusSuperadd start");
                List<CommissionSuperadd> commissionSuperadds = commissionSuperaddService.selectNeedComputBonusSuperadd();
                if ((commissionSuperadds != null) && (commissionSuperadds.size() > 0)) {
                    for (CommissionSuperadd commissionSuperadd : commissionSuperadds) {
                        BonusLog bonusLog = bonusLogService.selectBonusLogByOrderCode(commissionSuperadd.getOrderCode());
                        if (bonusLog != null) {
                            continue;
                        }
                        bonusService.putoutBounsSupperadd(commissionSuperadd);

                    }
                }
                log.info("------------computBonusSuperadd end");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("computBonusSuperadd 异常信息：" + e.getMessage());
                throw new RuntimeException(e);
            }

        } else {
            log.info("computBonusSuperadd 有线程在执行");
        }
    }


    @Override
    public void synAccountCompare(String accountNo, int day, String batchCode) {
        ActionResult actionResult = new ActionResult();
        if (IceStringUtils.isNotBlank(accountNo)) {
            int count = 0;
            while (count < MAX_READTIMES) {
                log.info("------------同步对账");
                Date date = IceDateOperationUtils.addDays(new Date(), day - count);
                String nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
                String fileName = accountNo + nameDateStr + ACCOUNT_COMPARE_SUBFIX;
                File temFile = new File(CommonConstant.DZ_FTP_TMEP_PATH, fileName);
                if (!temFile.exists()) {
                    FtpResult result = FtpUtil.readFile(CommonConstant.DZ_FTP_HOST, CommonConstant.DZ_FTP_PASSWPRD, CommonConstant.DZ_FTP_USERNAME,
                            CommonConstant.DZ_FTP_PORT, CommonConstant.DZ_FTP_PATH, fileName, CommonConstant.DZ_FTP_CHARSET);
                    log.info("读取结果：\n" + IceFastJsonUtils.toJsonString(result));
                    if (result.isSuccess()) {
                        log.info(FtpUtil.downloadFile(CommonConstant.DZ_FTP_HOST, CommonConstant.DZ_FTP_PASSWPRD, CommonConstant.DZ_FTP_USERNAME,
                                CommonConstant.DZ_FTP_PORT, CommonConstant.DZ_FTP_PATH, fileName, CommonConstant.DZ_FTP_TMEP_PATH, fileName).getMessage());
                        if (result.getResultSet() != null) {
                            List<AccountCompare> accountCompares = transStringToAccountCompare(result.getResultSet(), accountNo, batchCode);
                            //入库
                            accountCompareService.saveAccountCompareList(accountCompares);

                        }
                        actionResult.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
                        actionResult.setMessage("同步成功");
                        break;
                    } else {
                        log.info("文件 " + CommonConstant.JF_FTP_PATH + "/" + fileName + "读取失败 尝试读取前一天文件...");
                        actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                        actionResult.setMessage(result.getMessage());
                    }
                } else {
                    log.info("文件已经读取过：" + IceFastJsonUtils.toJsonString(temFile));
                    break;
                }
                count++;
            }
            log.info("------------同步对账结束");
            logService.addLog(actionResult, "同步对账", "同步对账", CommonConstant.INTERFACE_TYPE_SYNFACCOUTCOMPARE);
        }

    }

    @Override
    public void synAccountCompare(int day) {
        List<Woaccount> woaccountList = woaccountService.selectAllAccount();
        String batchCode = IceRandomUtils.longUUID();
        if (woaccountList != null) {
            for (Woaccount woaccount : woaccountList) {
                synAccountCompare(woaccount.getMerNo(), day, batchCode);
            }
        }

    }


    @Override
    public void writOrderToTempPath(String method, int day, String dataStr) {
        Date date;
        String nameDateStr;
        List<OrderChannel> orderChannelList;
        String fileName = "";
        String content = "";
        String dateStr;
        switch (method) {
            case "orderChannel":
                date = IceDateOperationUtils.addDays(new Date(), day);
                nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
                orderChannelList = orderChannelService.selectOrderChannelListJF(null);
                //   List<OrderChannel> orderChannelListxxh = orderChannelService.selectOrderChannelListXXH(null);
                //    orderChannelList.addAll(orderChannelListxxh);
                //    orderChannelList.addAll(orderChannelListxxh);
                fileName = CommonConstant.FILE_NAME_PREFIX_SYNORDERCHANNEL + nameDateStr +
                        CommonConstant.FILE_NAME_EXTEND_SYNORDERCHANNEL +
                        CommonConstant.FILE_NAME_SUBFIX_SYNORDERCHANNEL;
                content = getContentList(orderChannelList, fileName);
                break;
            case "orderChannelMonth":
                date = IceDateOperationUtils.addMonths(new Date(), day);
                dateStr = IceDateFormatUtils.dateToString(date, "yyyy-MM");
                nameDateStr = IceDateFormatUtils.dateToString(new Date(), "yyyyMMdd");
                orderChannelList = orderChannelService.selectOrderChannelMonthListJF(dateStr);
                List<OrderChannel> orderChannelListxxh = orderChannelService.selectOrderChannelMonthListXXH(dateStr);
                orderChannelList.addAll(orderChannelListxxh);
                log.info("------------同步orderIchannel:" + IceFastJsonUtils.toJsonString(orderChannelList));
                fileName = CommonConstant.FILE_NAME_PREFIX_SYNORDERCHANNEL_MONTH + nameDateStr +
                        CommonConstant.FILE_NAME_EXTEND_SYNORDERCHANNEL_MONTH +
                        CommonConstant.FILE_NAME_SUBFIX_SYNORDERCHANNEL_MONTH;

                content = getContentListMonth(orderChannelList, fileName);
                break;
            case "orderActivityStaff":
                orderChannelList = orderChannelService.selectActivityStaff(dataStr);
                fileName = ACTIVITY_STAFF_FILENAME + dataStr + ACTIVITY_STAFF_FILENAME_SUBFIX;
                content = getAcitvitySaffContent(orderChannelList);

                break;
            default:
        }
        FileUtil.write(fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void synRedPackageOrder(int day) {
        //1、拼文件名
        String fileName = getRedPackageOrderFileName(day);
        //2、查询订单 转换红包信息
        List<RedPacketOrder> redPacketOrderList = redPacketOrderService.selectRedPackageOrder(day);
        //3、换地市编码
        redPacketOrderList = cityCodeService.transCityCodeForRedPackageOrder(redPacketOrderList);
        // 过滤掉不规范的数据

        //4、入库
        redPacketOrderService.insertList(redPacketOrderList);
        //5、转换为文档内容
        String content = getFileContent(redPacketOrderList);
        log.info(" 上传内容：" + content);
        //6、同步文件到ftp
        uploadFile(fileName, content);
    }

    private void uploadFile(String fileName, String content) {
        SFTPUtil sftp = new SFTPUtil(CommonConstant.RED_PACKAGE_SFTP_USERNAME, CommonConstant.RED_PACKAGE_SFTP_PASSWORD,
                CommonConstant.RED_PACKAGE_SFTP_HOST, CommonConstant.RED_PACKAGE_SFTP_PORT);

        FileUtil.write(fileName, content, CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH);
        String tempFile = CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH + "/" + fileName;
        try {
            sftp.login();
            sftp.upload(CommonConstant.RED_PACKAGE_SFTP_UPLOAD_PATH, tempFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("文件生成失败");
            throw new RuntimeException(e);
        } catch (SftpException e) {
            e.printStackTrace();
            log.error("文件上传失败");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }
    }

    private String getFileContent(List<RedPacketOrder> redPacketOrderList) {
        StringBuilder stringBuilder = new StringBuilder();
        if (redPacketOrderList != null && !redPacketOrderList.isEmpty()) {
            for (RedPacketOrder redPacketOrder : redPacketOrderList) {
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getOrderCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getOrderTel(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getTelSubordinateSystem(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getChannelCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getProvinceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getOrderDate(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getRedPacketCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(redPacketOrder.getMoney(), ""));
                stringBuilder.append("\n");
            }
        }
        return stringBuilder.toString();
    }


    private String getRedPackageOrderFileName(int day) {
        String dateStr = IceDateFormatUtils.dateToString(IceDateOperationUtils.addDays(new Date(), day), "yyyyMMddHHmmss");

        return RED_PACKAGE_ORDER_PREFIX + CommonConstant.MERCHANT_CODE
                + "_" + dateStr
                + "_" + IceRandomUtils.randomNumeric(4)
                + RED_PACKAGE_ORDER_SUBFIX;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void synRedPackageOrderResult(int day) {
        //查询目录下所有文件
        SFTPUtil sftp = new SFTPUtil(CommonConstant.RED_PACKAGE_SFTP_USERNAME, CommonConstant.RED_PACKAGE_SFTP_PASSWORD,
                CommonConstant.RED_PACKAGE_SFTP_HOST, CommonConstant.RED_PACKAGE_SFTP_PORT);
        try {

            sftp.login();
            List<String> fileNames = sftp.listFileNames(CommonConstant.RED_PACKAGE_SFTP_DOWNLOAD_PATH);
            //匹配文件名
            for (String fileName : fileNames) {
                if (fileName.contains(RED_PACKAGE_ORDER_PREFIX) && fileName.contains(RED_PACKAGE_ORDER_RESULT_SUBFIX)
                        && (fileName.contains(IceDateFormatUtils.dateToString(IceDateOperationUtils.addMonths(new Date(), -1), "yyyyMM"))
                        || fileName.contains(IceDateFormatUtils.dateToString(new Date(), "yyyyMM")))) {
                    File temFile = new File(CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH, fileName);
                    if (temFile.exists()) {
                        continue;
                    }
                    //如果匹配成功 并没有下载过，下载并读取
                    sftp.download(CommonConstant.RED_PACKAGE_SFTP_DOWNLOAD_PATH, fileName, CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH);
                    File downLoadFile = new File(CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH, fileName);
                    if (downLoadFile.exists()) {
                        List<String> content = FileUtil.readFileContentList(downLoadFile, "utf-8");
                        //转换对象
                        List<RedPacketOrderResult> redPacketOrderResultList = tannsDateToRedPacketResult(content);
                        //入库
                        redPacketOrderResultService.insertList(redPacketOrderResultList);
                    }
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
            log.info("sftp 异常");
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("文件没有找到");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }

    }

    @Override
    public void synUnicomPyaReq() {
        //查询目录下所有文件
        SFTPUtil sftp = new SFTPUtil(CommonConstant.UNICOMPAY_SFTP_USERNAME, CommonConstant.UNICOMPAY_SFTP_PASSWORD,
                CommonConstant.UNICOMPAY_SFTP_HOST, CommonConstant.UNICOMPAY_SFTP_PORT);
        try {
            sftp.login();
            List<String> fileNames = sftp.listFileNames(CommonConstant.UNICOMPAY_SFTP_DOWNLOAD_PATH);
            //匹配文件名
            for (String fileName : fileNames) {
                log.info("fileName:" + fileName);
                if (fileName.contains(CommonConstant.TX_UNICOMPAY) && fileName.contains(UNICOMPAY_FILE_RESULT_SUBFIX)
                        && (fileName.contains(IceDateFormatUtils.dateToString(IceDateOperationUtils.addMonths(new Date(), -1), "yyyyMM"))
                        || fileName.contains(IceDateFormatUtils.dateToString(new Date(), "yyyyMM")))) {
                    File temFile = new File(CommonConstant.UNICOMPAY_SFTP_TEMP_PATH, fileName);
                    if (temFile.exists()) {
                        continue;
                    }
                    //如果匹配成功 并没有下载过，下载并读取
                    sftp.download(CommonConstant.UNICOMPAY_SFTP_DOWNLOAD_PATH, fileName, CommonConstant.UNICOMPAY_SFTP_TEMP_PATH);
                    File downLoadFile = new File(CommonConstant.UNICOMPAY_SFTP_TEMP_PATH, fileName);
                    if (downLoadFile.exists()) {
                        List<String> content = FileUtil.readFileContentList(downLoadFile, "utf-8");
                        log.info("联通支付回盘文件读取内容：" + IceFastJsonUtils.toJsonString(content));
                        //转换对象
                        List<UnicomPayReq> unicomPayReqs = transDateToUnicomPayReq(content);
                        unicomPayReqService.saveUnicomPayReqList(unicomPayReqs);
                        edtApiService.callBackIchannel(unicomPayReqs);
                    }
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
            log.info("sftp 异常");
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("文件没有找到");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }

    }


    @Override
    public void synUnicomPyaReqBatch() {
        //查询目录下所有文件
        SFTPUtil sftp = new SFTPUtil(CommonConstant.UNICOMPAY_SFTP_USERNAME, CommonConstant.UNICOMPAY_SFTP_PASSWORD,
                CommonConstant.UNICOMPAY_SFTP_HOST, CommonConstant.UNICOMPAY_SFTP_PORT);
        try {
            sftp.login();
            List<String> fileNames = sftp.listFileNames(CommonConstant.UNICOMPAY_SFTP_DOWNLOAD_PATH);
            //匹配文件名
            int count = 0;
            for (String fileName : fileNames) {
                String dayFileName = CommonConstant.TX_UNICOMPAY + IceDateFormatUtils.dateToString(IceDateOperationUtils.addDays(new Date(), -count), "yyyyMMdd") + UNICOMPAY_FILE_RESULT_SUBFIX;
                if (fileName.equals(dayFileName)) {
                    //如果匹配成功 并没有下载过，下载并读取
                    sftp.download(CommonConstant.UNICOMPAY_SFTP_DOWNLOAD_PATH, fileName, CommonConstant.UNICOMPAY_BATCH_SFTP_TEMP_PATH);
                    File downLoadFile = new File(CommonConstant.UNICOMPAY_BATCH_SFTP_TEMP_PATH, fileName);
                    if (downLoadFile.exists()) {
                        List<String> content = FileUtil.readFileContentList(downLoadFile, "utf-8");
                        if (content != null && content.size() > 0) {
                            for (String s : content) {
                                log.info(s);
                            }
                        }

                    }
                    break;
                }
                count++;
            }
        } catch (SftpException e) {
            e.printStackTrace();
            log.info("sftp 异常");
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("文件没有找到");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }
    }

    @Override
    public void synUnicomPyaReqBatchState() {
        //查询目录下所有文件
        SFTPUtil sftp = new SFTPUtil(CommonConstant.UNICOMPAY_SFTP_USERNAME, CommonConstant.UNICOMPAY_SFTP_PASSWORD,
                CommonConstant.UNICOMPAY_SFTP_HOST, CommonConstant.UNICOMPAY_SFTP_PORT);
        try {
            sftp.login();
            List<String> fileNames = sftp.listFileNames(CommonConstant.UNICOMPAY_SFTP_DOWNLOAD_PATH);
            //匹配文件名
            int count = 0;
            for (String fileName : fileNames) {
                String dayFileName = CommonConstant.TX_UNICOMPAY + IceDateFormatUtils.dateToString(IceDateOperationUtils.addDays(new Date(), -count), "yyyyMMdd") + "_status.REQ";
                if (fileName.equals(dayFileName)) {
                    //如果匹配成功 并没有下载过，下载并读取
                    sftp.download(CommonConstant.UNICOMPAY_SFTP_DOWNLOAD_PATH, fileName, CommonConstant.UNICOMPAY_BATCH_SFTP_TEMP_PATH);
                    File downLoadFile = new File(CommonConstant.UNICOMPAY_BATCH_SFTP_TEMP_PATH, fileName);
                    if (downLoadFile.exists()) {
                        List<String> content = FileUtil.readFileContentList(downLoadFile, "utf-8");
                        if (content != null && content.size() > 0) {
                            for (String s : content) {
                                log.info(s);
                            }
                        }
                    }
                    break;
                }
                count++;
            }
        } catch (SftpException e) {
            e.printStackTrace();
            log.info("sftp 异常");
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("文件没有找到");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }
    }

    @Override
    public void selectFirstMoneyByOrderCode(String orderCode, String type) {
        if (IceStringUtils.isNotBlank(orderCode)) {
            OrderChannel orderChannel = orderChannelService.selectOrderCHannelByOrderCode(orderCode);

            if ("1".equals(type)) {
                commissionService.setCommissiont(orderChannel);
            } else {
                computeCommissionKdService.selectFirstMoneyAndComputCommissionMoney(orderChannel);
            }
        }
    }

    @Override
    public void putOutCommissionByOrderCode(String orderCode, String type) {
        if (IceStringUtils.isNotBlank(orderCode)) {
            if ("1".equals(type)) {
                OrderCreditCK orderCreditCK = orderCreditCKService.selectOrderCreditCkByOrderCode(orderCode);
                putoutCommissionService.putoutCommissionCk(orderCreditCK);
            } else {
                OrderCreditKd orderCreditKd = orderCreditKdService.selectOrderCreditKdByOrderCode(orderCode);
                putoutCommissionService.putoutCommissionKd(orderCreditKd);
            }
        }

    }

    @Override
    public void moveDataToOrderCreditByOrderCode(String orderCode, String type) {
        if (IceStringUtils.isNotBlank(orderCode)) {
            if ("1".equals(type)) {
                commissionService.moveOrderCreditCkToOrderCreditByOrderCode(orderCode);
            } else {
                computeCommissionKdService.moveOrderCreditKdToOrderCreditByOrderCode(orderCode);
            }
        }

    }

    @Override
    public void computBounsMoneyByOrderCode(String orderCode) {
        if (IceStringUtils.isNotBlank(orderCode)) {
            OrderCredit orderCredit = orderCreditService.selectByOrderCode(orderCode);
            bonusService.setBonus(orderCredit);
        }

    }

    @Override
    public void selectFirstMoneyCkC() {

        String key = "SELECTFIRSTMONEYCKC";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------selectFirstMoneyCkC start");
                List<OrderChannel> orderChannels = orderChannelService.selectOrderChannelCkCWithoutCommissionByDay(null);
                if (orderChannels != null && orderChannels.size() > 0) {

                    for (OrderChannel orderChannel :
                            orderChannels) {
                        onlineOrderService.computCommissionSingle(orderChannel);
                    }
                }
                log.info("-----------------selectFirstMoneyCkC end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error(" C 计算成卡佣金异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("C 计算成卡佣金有线程在执行");
        }
    }

    @Override
    public void selectFirstMoneyKdC() {

        String key = "SELECTFIRSTMONEYKDC";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------selectFirstMoneyKdC start");
                List<OrderChannel> orderChannels = orderChannelService.selectOrderChannelKdCWithoutCommissionByDay(null);
                if (orderChannels != null && orderChannels.size() > 0) {

                    for (OrderChannel orderChannel :
                            orderChannels) {
                        onlineOrderService.computCommissionRelation(orderChannel);
                    }
                }
                log.info("-----------------selectFirstMoneyKdC end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error(" C 计算宽带佣金异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("C 计算宽带佣金有线程在执行");
        }
    }

    @Override
    public void selectUserIdC() {


        String key = "SELECTUSERIDC";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------selectUserIdC start");
                List<OrderCreditCK> orderCreditCKS = orderCreditCKService.selectOrderChannelCNeedPush();
                if (orderCreditCKS != null && orderCreditCKS.size() > 0) {

                    for (OrderCreditCK orderCreditCK :
                            orderCreditCKS) {
                        onlineOrderService.selectUserIdRelation(orderCreditCK);
                    }
                }
                log.info("-----------------selectUserIdC end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error(" C 查询userid异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("C 查询uiserid线程在执行");
        }
    }

    @Override
    public void computCommissionBf() {
        String key = "COMPUTCOMMISSIONBF";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------computCommissionBf start");
                List<ContinueCommissionRule> continueCommissionRules = bfService.getAllContinueCommissionRules();
                if (continueCommissionRules != null && continueCommissionRules.size() > 0) {
                    for (ContinueCommissionRule continueCommissionRule :
                            continueCommissionRules) {
                        List<OrderChannel> orderChannels = bfService.getNeedBFOrder(continueCommissionRule.getCityCode(),
                                continueCommissionRule.getContinuitionDay(), continueCommissionRule.getProductId(), continueCommissionRule.getType());
                        if (orderChannels != null && orderChannels.size() > 0) {
                            for (OrderChannel orderChannel :
                                    orderChannels) {
                                bfService.computContinueCommission(orderChannel, continueCommissionRule);
                            }
                        }

                    }
                }
                log.info("-----------------computCommissionBf end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error(" computCommissionBf异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("查询computCommissionBf线程在执行");
        }


    }

    @Override
    public void putoutCommissionBf() {
        String key = "PUTOUTCOMMISSIONBF";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------putoutCommissionBf start");
                List<OrderCreditBf> orderCreditBfs = bfService.getAllNeedPutOut();
                if (orderCreditBfs != null && orderCreditBfs.size() > 0) {
                    for (OrderCreditBf orderCreditBf :
                            orderCreditBfs) {
                        bfService.putOutCommissionBf(orderCreditBf);
                    }
                }
                log.info("-----------------putoutCommissionBf end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("putoutCommissionBf异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("putoutCommissionBf线程在执行");
        }


    }

    @Override
    public void computeCommissionMonth() {

        String key = "COMPUTECOMMISSIONMONTH";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                //查询 ordercreditkd 中 没有发放的数据，即在m_account_log 中没有的数据
                log.info("computeCommissionMonth start");
                orderCreditMonthService.computerCommissionMonty();
                log.info("computeCommissionMonth end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("computeCommissionMonth异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }
        } else {
            log.info("computeCommissionMonth有线程在执行");
        }


    }

    @Override
    public void putoutCommissionMonth() {
        String key = "PUTOUTCOMMISSIONMONTH";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------putOrderCreditMonth start");
                List<OrderCreditMonth> orderCreditMonths = orderCreditMonthService.getAllNeedPutOut();
                if (orderCreditMonths != null && orderCreditMonths.size() > 0) {
                    for (OrderCreditMonth orderCreditMonth :
                            orderCreditMonths) {
                        putoutCommissionService.putoutCommissionMonth(orderCreditMonth);
                    }
                }
                log.info("-----------------putOrderCreditMonth end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("putOrderCreditMonth ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("putOrderCreditMonth 有线程在执行");
        }


    }

    @Override
    public void putOutCommissionSuperadd() {
        String key = "PUTOUTCOMMISSIONSUPERADD";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------putOutCommissionSuperadd start");
                List<CommissionSuperadd> commissionSuperadds = commissionSuperaddService.getAllNeedPutOut();
                if (commissionSuperadds != null && commissionSuperadds.size() > 0) {
                    for (CommissionSuperadd commissionSuperadd :
                            commissionSuperadds) {
                        putoutCommissionService.putOutCommissionSuperadd(commissionSuperadd);
                    }
                }
                log.info("-----------------putOutCommissionSuperadd end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("putOutCommissionSuperadd ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("putOutCommissionSuperadd 有线程在执行");
        }

    }

    @Override
    public void selectCommissionFirstOrder() {
        String key = "SELECTCOMMISSIONFIRSTORDER";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                //查询规则
                List<FirstOrderCommission> firstOrderCommissions = firstOrderCommissionService.getAllFirstOrderCommission();
                //循环规则，取产品，地市，时间段类型 查询时间段内第一单结算佣金的订单
                for (FirstOrderCommission firstOrderCommission :
                        firstOrderCommissions) {
                    //将订单保存到佣金追加表
                    firstOrderCommissionService.selectFirstCommissionAndSaveSuperadd(firstOrderCommission.getProductId(), firstOrderCommission.getCityCode(),
                            firstOrderCommission.getBeginDate(), firstOrderCommission.getEndDate(),
                            firstOrderCommission.getCommissionMoney(),firstOrderCommission.getType());
                }
                log.info("-----------------selectCommissionFirstOrder end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("selectCommissionFirstOrder ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("selectCommissionFirstOrder 有线程在执行");
        }


    }

    @Override
    public void selectCommissionArrive(String monthStr) {

        String key = "SELECTCOMMISSIONARRIVE";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                //查询包含要查询月的规则
                List<CommissionArriveRule> commissionArriveRules = commissionArriveRuleService.selectCommissionArriveRuleByMonthStr(monthStr);
                // 循环规则，取产品，地市，月份 查询达量有效订单，并将佣金追加
                for (CommissionArriveRule commissionArriveRule :
                        commissionArriveRules) {
                    commissionArriveService.selectCommissionArriveAndSaveSuperadd(commissionArriveRule.getCityCode(),
                            commissionArriveRule.getId(), commissionArriveRule.getCommissionMoney(), monthStr,
                            commissionArriveRule.getCountUp(), commissionArriveRule.getCountDown(),
                            commissionArriveRule.getBeginDate(), commissionArriveRule.getEndDate(),commissionArriveRule.getType());
                }
                log.info("-----------------selectCommissionArrive end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("selectCommissionArrive ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("selectCommissionArrive 有线程在执行");
        }


    }

    @Override
    public void synOrderIchannelDayForFXQYZX(int day) {
        ActionResult result = new ActionResult();
        try {
            log.info("------------同步synOrderIchannelDayForFXQYZX");
            Date date = IceDateOperationUtils.addDays(new Date(), day);
            String dayStr = IceDateFormatUtils.dateToString(date, "yyyy-MM-dd");
            String nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
            List<OrderChannel> orderChannelList = orderChannelService.selectOrderChannelDayForFXQYZX(dayStr);
            String fileName = "D07" + nameDateStr + "001" + ".TXT";
            String content = getContentListDayForFXQYZX(orderChannelList, fileName);
            FtpUtil.uploadFileAndSaveTempByInitiative(CommonConstant.FXQYZX_FTP_HOST, CommonConstant.FXQYZX_FTP_PASSWPRD,
                    CommonConstant.FXQYZX_FTP_USERNAME, CommonConstant.FXQYZX_FTP_PORT,
                    CommonConstant.FXQYZX_FTP_PATH, fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
            log.info("------------getContentListDayForFXQYZX上传文件结束");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
        }
        logService.addLog(result, "放心权益中心同步日成功订单订单", "放心权益中心同步日成功订单订单", CommonConstant.INTERFACE_TYPE_SYNORDERCHANNELFXQYZX);

    }

    @Override
    public void pushUseridByOrderCode(String orderCode) {
        OrderCreditCK orderCreditCK = orderCreditCKService.selectOrderCreditCkByOrderCode(orderCode);
        onlineOrderService.selectUserIdRelation(orderCreditCK);
    }

    @Override
    @Async
    public void testAsync() {
       log.info("--------------------------测试线程池");
    }

    private String getContentListDayForFXQYZX(List<OrderChannel> orderChannels, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fileName).append(CommonConstant.SPLIT_CHAR_SG).append(orderChannels.size()).append("\n");
        if (!orderChannels.isEmpty()) {
            for (OrderChannel orderChannel : orderChannels) {
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getServiceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(orderChannel.getOrderDate() == null ? "" : IceDateFormatUtils.dateToString(orderChannel.getOrderDate(), "yyyyMMddHHmmss"));
                stringBuilder.append("\n");
            }

        }
        return stringBuilder.toString();

    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void computRedpacketCount() {
        synDataDao.computRedPacketCount();
    }

    @Override
    public void synMechanismsOld() {
        ActionResult result = new ActionResult();
        try {
            log.info("------------同步组织结构开始");
            synDataDao.synMechanismsInfo();
            mechanismsService.updateAllCityCode();
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
            log.info("------------同步组织结构结束");
        } catch (Exception e) {

            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        logService.addLog(result, "同步组织机构", "同步组织机构", CommonConstant.INTERFACE_TYPE_SYNMECHANISMS);
    }

    @Override
    public void synStaffOld() {
        ActionResult result = new ActionResult();
        try {
            log.info("------------同步人员开始");
            synDataDao.synHrStaff();
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
            log.info("------------同步人员结束");
        } catch (Exception e) {
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        logService.addLog(result, "同步人员", "同步人员", CommonConstant.INTERFACE_TYPE_SYNSTAFF);
    }


    @Override
    public ActionResult synActivityStaff(String dataStr) {
        ActionResult result = new ActionResult();
        if (IceStringUtils.isBlank(dataStr)) {
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage("参数为空");
            return result;
        }
        try {
            List<OrderChannel> orderChannelList = orderChannelService.selectActivityStaff(dataStr);
            log.info("------------同步orderIchannel:" + IceFastJsonUtils.toJsonString(orderChannelList));
            String fileName = ACTIVITY_STAFF_FILENAME + dataStr + ACTIVITY_STAFF_FILENAME_SUBFIX;
            File temFile = new File(CommonConstant.JF_FTP_TMEP_PATH, fileName);
            if (!temFile.exists()) {
                String content = getAcitvitySaffContent(orderChannelList);
                FtpUtil.uploadFileAndSaveTemp(CommonConstant.JF_FTP_HOST, CommonConstant.JF_FTP_PASSWPRD,
                        CommonConstant.JF_FTP_USERNAME, CommonConstant.JF_FTP_PORT,
                        CommonConstant.JF_FTP_PATH, fileName, content, CommonConstant.JF_FTP_TMEP_PATH);
                log.info("------------orderIchannel上传文件结束");
                result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
                result.setMessage("生成文件成功：" + fileName);
            } else {
                result.setMessage("该文件已经生成过：" + fileName);
                result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
        }
        logService.addLog(result, "同步人员活动", "同步人员活动", CommonConstant.INTERFACE_TYPE_SYNACTIVITYSTAFF);
        return result;
    }

    @Override
    public void synAllExpansion(String dataStr) {
        ActionResult result = new ActionResult();
        SFTPUtil sftp = new SFTPUtil(CommonConstant.WG_SFTP_USERNAME, CommonConstant.WG_SFTP_PASSWORD,
                CommonConstant.WG_SFTP_HOST, CommonConstant.WG_SFTP_PORT);
        try {
            sftp.login();
            log.info("------------同步synAllExpansion");
            Date date = IceDateOperationUtils.addDays(new Date(), -1);
            String nameDateStr = IceDateFormatUtils.dateToString(date, "yyyyMMdd");
            List<Expansion> expansionList = expansionService.getExpansionList(dataStr);
            String fileName = "D06" + nameDateStr + "001" + ".TXT";
            String content = getExpansionListContent(expansionList, fileName);
            FileUtil.write(fileName, content, CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH);
            String tempFile = CommonConstant.RED_PACKAGE_SFTP_TEMP_PATH + "/" + fileName;

            sftp.upload(CommonConstant.WG_SFTP_UPLOAD_PATH, tempFile);
            log.info("------------synAllExpansion上传文件结束");
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            result.setMessage("同步成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
            log.error("文件生成失败");
            throw new RuntimeException(e);
        } catch (SftpException e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
            log.error("文件上传失败");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }
        logService.addLog(result, "同步合伙人日全量信息", "同步合伙人日全量信息", CommonConstant.INTERFACE_TYPE_SYNALLEXPANSION);
    }

    @Override
    public void selectFirstMoneyCk() {
        String key = "SELECTFIRSTMONEYCK";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------selectFirstMoneyCk start");
                List<OrderChannel> orderChannels = orderChannelService.selectOrderChannelCkWithoutCommissionByDay(null);
                if (orderChannels != null && orderChannels.size() > 0) {

                    for (OrderChannel orderChannel :
                            orderChannels) {
                        commissionService.setCommissiont(orderChannel);
                    }
                }
                log.info("-----------------selectFirstMoneyCk end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("计算成卡佣金异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("计算成卡佣金有线程在执行");
        }

    }

    @Override
    public void selectFirstMoneyKd() {

        String key = "SELECTFIRSTMONEYKD";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------selectFirstMoneyKd start");
                //查询宽带号码不为空的订单
                List<OrderChannel> orderChannels = orderChannelService.selectOrderChannelKdWithoutCommissionByDay(null);
                for (OrderChannel orderChannel :
                        orderChannels) {
                    computeCommissionKdService.selectFirstMoneyAndComputCommissionMoney(orderChannel);
                }
                log.info("-----------------selectFirstMoneyKd end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("计算宽带佣金异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }

        } else {
            log.info("计算宽带佣金有线程在执行");
        }
    }

    @Override
    public void moveDataToOrderCreditCk() {

        String key = "MOVEDATATOORDERCREDITCK";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------moveDataToOrderCreditCk start");
                commissionService.moveOrderCreditCkToOrderCredit();
                log.info("-----------------moveDataToOrderCreditCk end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("移动成卡数据异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }
        } else {
            log.info("移动成卡数据有线程在执行");
        }

    }

    @Override
    public void moveDataToOrderCreditKd() {

        String key = "MOVEDATATOORDERCREDITKD";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------moveDataToOrderCreditKd start");
                computeCommissionKdService.moveOrderCreditKdToOrderCredit();
                log.info("-----------------moveDataToOrderCreditKd end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("移动宽带数据异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }
        } else {
            log.info("移动宽带数据有线程在执行");
        }
    }

    @Override
    public void putOutCommissionCK() {

        String key = "PUTOUTCOMMISSIONCK";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                log.info("-----------------putOutCommissionCK start");
                //查询 ordercreditkd 中 没有发放的数据，即在m_account_log 中没有的数据
                List<OrderCreditCK> orderCreditCKs = orderCreditCKService.selectNeedPutOut();
                if (orderCreditCKs != null && orderCreditCKs.size() > 0) {
                    for (OrderCreditCK orderCreditCk :
                            orderCreditCKs) {

                        putoutCommissionService.putoutCommissionCk(orderCreditCk);
                    }
                }
                log.info("-----------------putOutCommissionCK end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("发放成卡数据数据异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }
        } else {
            log.info("发放成卡佣金有线程在执行");
        }
    }

    @Override
    public void putOutCommissionKd() {


        String key = "PUTOUTCOMMISSIONKD";
        if (redisTemplate.opsForValue().setIfAbsent(key, IceDateFormatUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"))) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            try {
                //查询 ordercreditkd 中 没有发放的数据，即在m_account_log 中没有的数据
                log.info("putOutCommissionKd start");
                List<OrderCreditKd> orderCreditKds = orderCreditKdService.selectNeedPutOut();
                if (orderCreditKds != null && orderCreditKds.size() > 0) {
                    for (OrderCreditKd orderCreditKd :
                            orderCreditKds) {
                        putoutCommissionService.putoutCommissionKd(orderCreditKd);
                    }
                }
                log.info("putOutCommissionKd end");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("发放宽带数据数据异常 ：" + e.getMessage());
            } finally {
                redisTemplate.delete(key);
            }
        } else {
            log.info("发放宽带佣金有线程在执行");
        }

    }

    private String getExpansionListContent(List<Expansion> expansionList, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fileName).append(CommonConstant.SPLIT_CHAR_SG).append(expansionList.size()).append("\n");
        if (!expansionList.isEmpty()) {
            for (Expansion expansion : expansionList) {
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getAddressCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getAddressCityName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getDistrictCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getDistrictName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getExpansionCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getExpansionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getAddress(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getManager(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getPhone(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(IceDateFormatUtils.dateToString(expansion.getAddTime(), "yyyyMMddHHmmss"), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getTypeName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getExpansionFlagName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getExpansionLevelName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getExpansionType(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getDevCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getStaffName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(expansion.getStaffNo(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append("\n");
            }

        }
        return stringBuilder.toString();

    }

    private List<RedPacketOrderResult> tannsDateToRedPacketResult(List<String> content) {
        if (content == null) {
            return null;
        }
        List<RedPacketOrderResult> redPacketOrderResultList = new ArrayList<>();
        String batchCode = IceDateFormatUtils.dateToString(new Date(), "yyyyMMddHHmmss");
        for (String str : content) {
            String[] redPacketOrderReusltArray = str.split(CommonConstant.SPLIT_CHAR_ZYSG, -1);
            log.info("str:" + str);
            log.info("redPacketOrderReusltArray:" + redPacketOrderReusltArray.length);
            if (redPacketOrderReusltArray.length == CommonConstant.FIELD_COUNT_REDPACKET_RESULT) {
                RedPacketOrderResult redPacketOrderResult = new RedPacketOrderResult();
                redPacketOrderResult.setId(IceRandomUtils.longUUID());
                redPacketOrderResult.setOrderCode(redPacketOrderReusltArray[0]);
                redPacketOrderResult.setOrderTel(redPacketOrderReusltArray[1]);
                redPacketOrderResult.setTelSubordinateSystem(redPacketOrderReusltArray[2]);
                redPacketOrderResult.setChannelCode(redPacketOrderReusltArray[3]);
                redPacketOrderResult.setProvinceCode(redPacketOrderReusltArray[4]);
                redPacketOrderResult.setCityCode(redPacketOrderReusltArray[5]);
                redPacketOrderResult.setOrderDate(redPacketOrderReusltArray[6]);
                redPacketOrderResult.setRedPacketCode(redPacketOrderReusltArray[7]);
                redPacketOrderResult.setResultState(redPacketOrderReusltArray[8]);
                redPacketOrderResult.setResultRemark(redPacketOrderReusltArray[9]);
                redPacketOrderResult.setConductDate(redPacketOrderReusltArray[10]);
                redPacketOrderResult.setMoney(redPacketOrderReusltArray[11]);
                redPacketOrderResult.setBatchCode(batchCode);
                redPacketOrderResultList.add(redPacketOrderResult);
            } else {
                log.error("验证失败字符串：" + str);
            }

        }
        log.info("转换成功数据量：" + redPacketOrderResultList.size());
        return redPacketOrderResultList;
    }

    private List<UnicomPayReq> transDateToUnicomPayReq(List<String> content) {
        if (content == null) {
            return null;
        }
        List<UnicomPayReq> unicomPayReqs = new ArrayList<>();
        String batchCode = IceDateFormatUtils.dateToString(new Date(), "yyyyMMddHHmmss");
        for (String str : content) {
            log.info("str:" + str);
            String[] unicomPayReqtArray = str.split(CommonConstant.SPLIT_CHAR_ZYSG);
            if (unicomPayReqtArray.length == CommonConstant.FIELD_COUNT_UNICOMPAY_RESULT) {
                UnicomPayReq unicomPayReq = new UnicomPayReq();
                unicomPayReq.setBatchCode(batchCode);
                unicomPayReq.setId(IceRandomUtils.longUUID());
                unicomPayReq.setPayTradId(unicomPayReqtArray[1]);
                unicomPayReq.setPhone(unicomPayReqtArray[2]);
                unicomPayReq.setMoney(unicomPayReqtArray[3]);
                unicomPayReq.setProvinceCode(unicomPayReqtArray[4]);
                unicomPayReqs.add(unicomPayReq);
            } else {
                log.error("验证失败字符串：" + str);
            }

        }
        log.info("转换成功数据量：" + unicomPayReqs.size());
        return unicomPayReqs;
    }

    private List<EntityForKafkaUniBssInfo> transStringToKafkaUnibssInfo(Set<String> content) {
        if (content == null) {
            return null;
        }
        List<EntityForKafkaUniBssInfo> uniBssInfos = new ArrayList<>();
        for (String str : content) {
            String[] uniBssInfoArray = str.split(CommonConstant.SPLIT_CHAR_ZYSG, -1);
            log.info("str:" + str);
            if (uniBssInfoArray.length == 12) {
                EntityForKafkaUniBssInfo uniBssInfo = new EntityForKafkaUniBssInfo();
                uniBssInfo.setId(IceRandomUtils.longUUID());
                uniBssInfo.setRECV_FEE(uniBssInfoArray[0]);
                uniBssInfo.setRECV_TIME(uniBssInfoArray[1]);
                uniBssInfo.setUSER_ID(uniBssInfoArray[2]);
                uniBssInfo.setOPEN_DATE(uniBssInfoArray[3]);
                uniBssInfo.setIN_DATE(uniBssInfoArray[4]);
                uniBssInfo.setPRODUCT_ID(uniBssInfoArray[5]);
                uniBssInfo.setNET_TYPE_CODE(uniBssInfoArray[6]);
                uniBssInfo.setTRANS_IDO(uniBssInfoArray[7]);
                uniBssInfo.setRELATION_TYPE_CODE(uniBssInfoArray[8]);
                uniBssInfo.setDEVELOP_STAFF_ID(uniBssInfoArray[9]);
                uniBssInfo.setREMOVE_TAG(uniBssInfoArray[10]);
                uniBssInfo.setUSER_STATE_CODESET(uniBssInfoArray[11]);
                uniBssInfo.setCREATEDATE(new Date());
                uniBssInfos.add(uniBssInfo);
            } else {
                log.error("验证失败字符串：" + str);
            }

        }
        log.info("转换成功数据量：" + uniBssInfos.size());
        return uniBssInfos;
    }


    private String getContentList(List<OrderChannel> orderChannels, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fileName).append(CommonConstant.SPLIT_CHAR_SG).append(orderChannels.size()).append("\n");
        if (!orderChannels.isEmpty()) {
            for (OrderChannel orderChannel : orderChannels) {
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrderCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getServiceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(orderChannel.getOrderDate() == null ? "" : IceDateFormatUtils.dateToString(orderChannel.getOrderDate(), "yyyyMMddHHmmss"));
                stringBuilder.append("\n");
            }

        }
        return stringBuilder.toString();

    }

    private String getContentListMonth(List<OrderChannel> orderChannels, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fileName).append(CommonConstant.SPLIT_CHAR_SG).append(orderChannels.size()).append("\n");
        if (!orderChannels.isEmpty()) {
            for (OrderChannel orderChannel : orderChannels) {
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getAddressDistrictCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getAddressDistrictName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getServiceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(orderChannel.getOrderDate() == null ? "" : IceDateFormatUtils.dateToString(orderChannel.getOrderDate(), "yyyyMMddHHmmss"))
                        .append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCustomer(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPhone(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(orderChannel.getFirstDate() == null ? "" : IceDateFormatUtils.dateToString(orderChannel.getFirstDate(), "yyyyMMddHHmmss"))
                        .append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getFirstMoney(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrgId(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrgName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getDevCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getStaffName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPositionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPositionId(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                if (IceStringUtils.isBlank(orderChannel.getBonusMoney())) {
                    stringBuilder.append(CommonConstant.SPLIT_CHAR_SG);
                } else {
                    stringBuilder.append(IceNumberUtils.toInt(orderChannel.getBonusMoney(), 0) * 100).append(CommonConstant.SPLIT_CHAR_SG);
                }

                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getMechantCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getMechantName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrderCode(), ""));
                stringBuilder.append("\n");
            }

        }
        return stringBuilder.toString();

    }

    private String getContentListDay(List<OrderChannel> orderChannels, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fileName).append(CommonConstant.SPLIT_CHAR_SG).append(orderChannels.size()).append("\n");
        if (!orderChannels.isEmpty()) {
            for (OrderChannel orderChannel : orderChannels) {
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getAddressDistrictCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getAddressDistrictName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getServiceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(orderChannel.getOrderDate() == null ? "" : IceDateFormatUtils.dateToString(orderChannel.getOrderDate(), "yyyyMMddHHmmss"))
                        .append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCustomer(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPhone(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrgId(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrgName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getDevCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getStaffName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPositionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPositionId(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getMechantCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getMechantName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrderCode(), ""));
                stringBuilder.append("\n");
            }

        }
        return stringBuilder.toString();

    }

    private String getAcitvitySaffContent(List<OrderChannel> orderChannels) {
        StringBuilder stringBuilder = new StringBuilder();
        if (!orderChannels.isEmpty()) {
            for (OrderChannel orderChannel : orderChannels) {
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrderCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCityName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getDistrictCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getDistrictName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getExpansionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getProductCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getServiceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(orderChannel.getOrderDate() == null ? "" : IceDateFormatUtils.dateToString(orderChannel.getOrderDate(), "yyyyMMddHHmmss"))
                        .append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getCustomer(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPhone(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrgId(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getOrgName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getDevCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getStaffName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPositionName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(orderChannel.getPositionId(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append("\n");
            }

        }
        return stringBuilder.toString();

    }


    /**
     * 将数据转换为实体，已经去重，添加订单唯一验证
     *
     * @param resultSet 读到的结果集
     * @return java.util.List<com.edt.ichannel.api.entiy.local.OrderCredit>
     * 订单对象集合
     * @author 孙梁
     * 2018/6/4 15:00
     */
    private List<OrderCredit> transStringToOrderCredit(Set<String> resultSet) {
        if (resultSet == null) {
            return null;
        }
        String batchCode = IceRandomUtils.longUUID();
        Map<String, OrderCredit> orderCreditMap = new HashMap<>();
        for (String str : resultSet) {
            String[] orderCreditArray = str.split(CommonConstant.SPLIT_CHAR_ZYSG, -1);
            if (orderCreditArray.length == CommonConstant.FIELD_COUNT_FIRST_CHARGE) {
                OrderCredit orderCredit = new OrderCredit();
                orderCredit.setId(IceRandomUtils.longUUID());
                orderCredit.setOrderCode(orderCreditArray[0]);
                orderCredit.setCityCode(orderCreditArray[1]);
                orderCredit.setProductName(orderCreditArray[2]);
                orderCredit.setProductCode(orderCreditArray[3]);
                orderCredit.setServiceCode(orderCreditArray[4]);
                orderCredit.setOrderDate(IceStringUtils.isBlank(orderCreditArray[5]) ? null : IceDateFormatUtils.stringToDate(orderCreditArray[5], "yyyyMMddHHmmss"));
                orderCredit.setFirstDate(IceStringUtils.isBlank(orderCreditArray[6]) ? null : IceDateFormatUtils.stringToDate(orderCreditArray[6], "yyyyMMddHHmmss"));
                orderCredit.setFirstMoney(IceNumberUtils.toInt(orderCreditArray[7], 0));
                orderCredit.setAddTime(new Date());
                orderCredit.setBatchCode(batchCode);
                if (validateUnique(orderCredit)) {
                    orderCreditMap.put(orderCredit.getOrderCode(), orderCredit);
                }

            } else {
                log.error("验证失败字符串：" + str);
            }

        }
        log.info("转换成功数据量：" + orderCreditMap.size());
        return new ArrayList<>(orderCreditMap.values());
    }


    private List<AccountCompare> transStringToAccountCompare(Set<String> resultSet, String num, String batchCode) {
        if (resultSet == null) {
            return null;
        }
        List<AccountCompare> accountCompareList = new ArrayList<>();
        int count = 0;
        String accountNo = num;
        String accountName = "";
        String dealDate = "";
        for (String str : resultSet) {
            String[] accountCompareArray = str.split(CommonConstant.SPLIT_CHAR_ZYSG, -1);
            if (count == 0 || count == 3) {
                count++;
                continue;
            }
            if (count == 1) {
                accountNo = accountCompareArray[0];
                accountName = accountCompareArray[1];
                dealDate = accountCompareArray[6];
            }

            if (accountCompareArray.length == 10) {
                AccountCompare accountCompare = new AccountCompare();
                accountCompare.setId(IceRandomUtils.longUUID());
                accountCompare.setAccountNo(accountNo);
                accountCompare.setAccountName(accountName);
                accountCompare.setDealDate(dealDate);
                accountCompare.setTradeModeCode(accountCompareArray[0]);
                accountCompare.setTradeModeName(accountCompareArray[1]);
                accountCompare.setPayModeCode(accountCompareArray[2]);
                accountCompare.setPayModeName(accountCompareArray[3]);
                accountCompare.setAccountOrderDate(accountCompareArray[4]);
                accountCompare.setAccountOrderCode(accountCompareArray[5]);
                accountCompare.setPayOrderCode(accountCompareArray[6]);
                accountCompare.setPayOrderMoney(accountCompareArray[7]);
                accountCompare.setPaydetail(accountCompareArray[8]);
                accountCompare.setCommissionCharge(accountCompareArray[9]);
                accountCompare.setBatchCode(batchCode);
                accountCompareList.add(accountCompare);
            } else {
                log.error("验证失败字符串：" + str);
            }

        }
        log.info("转换成功数据量：" + accountCompareList.size());
        return accountCompareList;
    }


    /**
     * 单号唯一性验证
     *
     * @param orderCredit 订单对象
     * @author 孙梁
     * 2018/6/4 15:00
     */
    private boolean validateUnique(OrderCredit orderCredit) {
        if (orderCredit == null) {
            return false;
        }
        if (IceStringUtils.isBlank(orderCredit.getOrderCode())) {
            return false;
        }
        OrderCredit orderCreditDb = orderCreditService.selectByOrderCode(orderCredit.getOrderCode());
        return orderCreditDb == null;
    }

    private String getSelectFirstMoneyInfoMonth(List<FirstmoneyLog> firstmoneyLogs) {
        StringBuilder stringBuilder = new StringBuilder();
        if (firstmoneyLogs != null && firstmoneyLogs.size() > 0) {
            for (FirstmoneyLog firstmoneyLog : firstmoneyLogs) {
                stringBuilder.append(IceStringUtils.blankToDefault(firstmoneyLog.getServiceCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(firstmoneyLog.getOrderDate() == null ? "" : IceDateFormatUtils.dateToString(firstmoneyLog.getOrderDate(), "yyyyMMddHHmmss")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(firstmoneyLog.getMonthstr(), ""));
                stringBuilder.append("\n");
            }
        }
        return stringBuilder.toString();
    }

}
